﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Data.Linq;
using Utils;
using Settings;
using System.Reflection;

namespace SMSROUTER.Business
{
    public partial class SmsRouterReport
    {
        public static DBDataContext _dataContext = new SMSROUTER.Business.DBDataContext();

        public SmsRouterReport(int? routerID, Guid? smsOutGuid, string cooperateGUID, DateTime? sentTime, DateTime? reportTime, string status, int? threadID, string stringParam, byte[] binaryParam)
        {
            this.RouterID = routerID;
            this.SmsOutGUID = smsOutGuid;
            this.CooperateGUID = cooperateGUID;
            this.SentTime = sentTime;
            this.ReportTime = reportTime;
            this.Status = status;
            this.ThreadID = threadID;
            this.StringParam = stringParam;
            this.BinaryParam = binaryParam;
        }
        public SmsRouterReport(int? routerID, Guid? smsOutGuid, string cooperateGUID, DateTime? sentTime, DateTime? reportTime, string status, int? threadID)
        {
            this.RouterID = routerID;
            this.SmsOutGUID = smsOutGuid;
            this.CooperateGUID = cooperateGUID;
            this.SentTime = sentTime;
            this.ReportTime = reportTime;
            this.Status = status;
            this.ThreadID = threadID;
        }
        
        public static SmsRouterReport GetByID(int id)
        {
            try
            {
                return _dataContext.SmsRouterReports.FirstOrDefault(p => p.RouterID == id);
            }
            catch (Exception ex)
            {                
                throw ex;
            }
        }
        public static void Insert(SmsRouterReport obj)
        {
            try
            {
                _dataContext.SmsRouterReports.InsertOnSubmit(obj);
                _dataContext.SubmitChanges();
            }
            catch (Exception ex)
            {                
                throw ex;
            }
        }
        public static void Update(SmsRouterReport obj)
        {
            try
            {
                SmsRouterReport obj1 = _dataContext.SmsRouterReports.FirstOrDefault(p=>p.ReportID == obj.ReportID);
                if (obj1 != null)
                {
                    foreach (PropertyInfo pi in obj.GetType().GetProperties())
                    {
                        if (pi.CanWrite)
                        {
                            pi.SetValue(obj1, pi.GetValue(obj, null), null);
                        }
                    }
                    _dataContext.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void Save(SmsRouterReport obj)
        {
            try
            {
                SmsRouterReport obj1 = _dataContext.SmsRouterReports.FirstOrDefault(p => p.ReportID == obj.ReportID);
                if (obj1 != null)
                {
                    foreach (PropertyInfo pi in obj.GetType().GetProperties())
                    {
                        if (pi.CanWrite)
                        {
                            pi.SetValue(obj1, pi.GetValue(obj, null), null);
                        }
                    }
                    _dataContext.SubmitChanges();
                }
                else
                {
                    _dataContext.SmsRouterReports.InsertOnSubmit(obj);
                    _dataContext.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static List<SmsRouterReport> GetAll()
        {
            try
            {
                using (SqlDataReader rd = SqlHelper.ExecuteReader(AppSetting.ConnectionString, CommandType.StoredProcedure, "usp_SmsRouterReport_GetAll"))
                {
                    return ObjectClass.CreateList<SmsRouterReport>(rd);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static List<SmsRouterReport> GetByRouterID(int routerID)
        {
            try
            {
                using (SqlDataReader rd = SqlHelper.ExecuteReader(AppSetting.ConnectionString, CommandType.StoredProcedure, "usp_SmsRouterReport_GetByRouterID", new SqlParameter("@RouterID", routerID), new SqlParameter("@Status", AppSetting.Status.SENTGATEWAY)))
                {
                    return ObjectClass.CreateList<SmsRouterReport>(rd);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static List<SmsRouterReport> GetByRouterID(int routerID, long startID, int batchSize)
        {
            try
            {
                SqlParameter[] sqlParam = new SqlParameter[]{
                    new SqlParameter("@RouterID", routerID), 
                    new SqlParameter("@Status", AppSetting.Status.SENTGATEWAY),
                    new SqlParameter("@StartID", startID),
                    new SqlParameter("@BatchSize", batchSize)
                };
                using (SqlDataReader rd = SqlHelper.ExecuteReader(AppSetting.ConnectionString, CommandType.StoredProcedure, "usp_SmsRouterReport_PagingByRouterID", sqlParam))
                {
                    return ObjectClass.CreateList<SmsRouterReport>(rd);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void BulkInsert(IList<SmsRouterReport> list)
        {
            try
            {
                DataAccess.BulkInsert<SmsRouterReport>(list, "SmsRouterReport");
            }
            catch (Exception ex)
            {
                Log.InsertLog(ex, null, AppSetting.WarningType.mt_error, null);
                try
                {
                    Xml.WriteListToFile<SmsRouterReport>(list, AppSetting.SmsRouterReportBackupFileName);
                }
                catch (Exception ex1)
                {
                    Log.InsertLog("SmsRouterReport Write to Xml has fail|"+ex1.Message, ex1.StackTrace, ex1.Source, AppSetting.WarningType.mt_error, null);
                    //throw new Exception();
                }
            }
        }
        public static void BatchUpdate(IList<SmsRouterReport> list)
        {
            try
            {
                DataAccess.BatchExecute<SmsRouterReport>(list, "@SmsRouterReport", "SmsRouterReportTableType", "usp_SmsRouterReport_Update");
            }
            catch (Exception ex)
            {
                Log.InsertLog(ex, null, AppSetting.WarningType.mt_error, null);
            }
        }        
        public static void BatchDelete(IList<SmsRouterReport> list)
        {            
            try
            {
                DataAccess.BatchExecute<SmsRouterReport>(list, "@SmsRouterReport", "SmsRouterReportTableType", "usp_SmsRouterReport_Delete");
            }
            catch (Exception ex)
            {
                Log.InsertLog(ex, null, AppSetting.WarningType.mt_error, null);
            }
        }

        /// <summary>
        /// Update from SmsRouterReport to SmsOutReport with Satatus not equal to ExclusionStatus
        /// Example: if you want to Update with status != "SENTGATEWAY" then ExclusionStatus must be "SENTGATEWAY"
        /// </summary>
        /// <param name="exStatus">ExclusionStatus</param>
        public static void UpdateToOutReport(int routerID, string exStatus)
        {
            try
            {
                SqlParameter[] sqlParams = new SqlParameter[] { new SqlParameter("@RouterID", routerID), new SqlParameter("@ExStatus", exStatus) };
                DataAccess.Execute("usp_SmsRouterReport_UpdateToSmsOutReport", sqlParams);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static void ReadFromXmlFile()
        {
            try
            {
                string fileName = AppSetting.SmsRouterReportBackupFileName;
                if (System.IO.File.Exists(fileName))
                {
                    SqlConnection conn = AppSetting.GetConnection();
                    if (conn.State == ConnectionState.Open)
                    {
                        List<SmsRouterReport> listRouterReport = Xml.ReadFromFileToList<SmsRouterReport>(fileName);
                        // Xóa file xml sau khi đọc xong.
                        System.IO.File.Delete(fileName);

                        if (listRouterReport != null && listRouterReport.Count > 0)
                        {
                            BulkInsert(listRouterReport);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
